<template>
	<!-- @touchstart="closePop" -->
	<uni-popup ref="popupRef" type="bottom" @change="handlePopupChange" :safe-area="false">
		<view v-if="isShow" class="input_pop" :style="{ bottom: inputBottom + 'px', paddingBottom: paddingHeight + 'px' }">
			<view class="input">
				<textarea
					ref="textareaRef"
					:show-confirm-bar="false"
					:adjust-position="false"
					:focus="isFocus"
					:auto-height="true"
					:disable-default-padding="true"
					:hold-keyboard="true"
					:cursor-spacing="20"
					:placeholder="placeholder"
					class="input-inner"
					v-model="params.content"
					@focus="inputFocus"
					@blur="inputBlur"
					@confirm="confirmInput"
					@keyboardheightchange="onKeyboardHeightChange"
				/>
				<view class="imglist">
					<view class="items" v-for="(item, index) in params.images" :key="index">
						<image :src="item" mode="aspectFill"></image>
						<image src="/static/close.png" mode="" class="icon" @click="removeIMG(index)"></image>
					</view>
					<view class="items1 flex_jc_cent" @tap="chooseFENGMIAN">
						<uni-icons type="plusempty" color="#979797"></uni-icons>
					</view>
				</view>
			</view>
			<view class="button_f flex_jc_sb">
				<view class="" @tap="chooseFENGMIAN" v-if="verifyModel == 0">
					<image src="/static/xc.png" mode=""></image>
				</view>
				<view class="" v-else>
					
				</view>
				<view class="btn" :class="btnactive ? 'btn_active' : ''" @click="submitComment">发表</view>
			</view>
		</view>
	</uni-popup>
</template>

<script setup>
import { ref, nextTick, watch, onMounted, onUnmounted, getCurrentInstance, reactive, computed } from 'vue';
import { articleReply ,article} from '@/api/community.js';
import { chooseAndUploadImage } from '@/utils/upload';
import { toast, showConfirm } from '@/utils/common.js';

const popupRef = ref(null);
const textareaRef = ref(null);
const inputBottom = ref(0);
const keyboardHeight = ref(0);
const isAndroid = ref(false);
const isIOS = ref(false);
const isShow = ref(false);
const isFocus = ref(false);
const paddingHeight = ref(0);
const isSubmitting = ref(false);

// 页面状态管理
const pageVisible = ref(true);
const wasOpenedBeforeHide = ref(false);

const closePop = () => {
	console.log('关闭弹窗');
	popupRef.value.close();
	setTimeout(() => {
		isFocus.value = false;
		isSubmitting.value = false;
		inputBottom.value = 0;
		keyboardHeight.value = 0;
		isShow.value = false;
		wasOpenedBeforeHide.value = false;
		params.content = '';
		params.images = [];
	}, 100);
};
import { getConfig } from '@/api/login.js';
const verifyModel = ref(0)
onMounted(() => {
	const systemInfo = uni.getSystemInfoSync();
	isAndroid.value = systemInfo.platform === 'android';
	isIOS.value = systemInfo.platform === 'ios';
	console.log('平台检测:', isAndroid.value ? 'Android' : 'iOS');
	getConfig({}).then(res=>{
		if(res.code == 200){
			verifyModel.value = res.data.verifyModel
		}
	})
});

const btnactive = computed(() => {
	return params.content.trim().length > 0;
});

// 键盘高度变化 - 只处理布局，不处理聚焦
const onKeyboardHeightChange = (e) => {
	if (!pageVisible.value) return;

	const systemInfo = uni.getSystemInfoSync();
	paddingHeight.value = isAndroid.value ? 30 : systemInfo.safeAreaInsets.bottom || 10;

	if (e.detail.height > 0) {
		keyboardHeight.value = e.detail.height;
		inputBottom.value = e.detail.height - paddingHeight.value;
		console.log('键盘弹出，高度:', e.detail.height);
	} else {
		console.log('键盘收起');
		keyboardHeight.value = 0;
		inputBottom.value = 0;
	}
};

// 弹窗状态变化
const handlePopupChange = (e) => {
	if (!e.show) {
		isFocus.value = false;
		isSubmitting.value = false;
		inputBottom.value = 0;
		keyboardHeight.value = 0;
		isShow.value = false;
		wasOpenedBeforeHide.value = false;
		params.content = '';
		params.images = [];
	} else {
		isShow.value = true;
		// 打开弹窗时自动聚焦
		setTimeout(() => {
			isFocus.value = true;
		}, 300);
	}
};
const placeholder = ref('');
const sendType = ref(1);
// 打开弹窗
const open = (item, type) => {
	sendType.value = type;
	if (type == 2) {
		placeholder.value = '回复：' + item.user.name;
	} else {
		placeholder.value = '与人善言，暖于布帛';
	}
	params.id = item.id;
	if (popupRef.value) {
		isSubmitting.value = false;
		popupRef.value.open();
		setTimeout(() => {
			isShow.value = true;
			// 延迟自动聚焦
			setTimeout(() => {
				isFocus.value = true;
			}, 400);
		}, 100);
	}
};

// 输入框聚焦 - 只处理布局
const inputFocus = (e) => {
	console.log('输入框自然获得焦点');
	if (keyboardHeight.value === 0 && pageVisible.value) {
		const systemInfo = uni.getSystemInfoSync();
		paddingHeight.value = isAndroid.value ? 30 : systemInfo.safeAreaInsets.bottom || 10;
		inputBottom.value = (isAndroid.value ? 30 : e.detail.height || 50) - paddingHeight.value;
	}
};

// 输入框失去焦点 - 不再重新聚焦
const inputBlur = (e) => {
	console.log('输入框自然失去焦点');
	// 什么都不做，让系统自然处理
};

const removeIMG = (index) => {
	params.images.splice(index, 1);
};

const chooseFENGMIAN = async (e) => {
	// 选择图片时失去焦点
	try {
		const remainingCount = 9 - params.images.length;
		if (remainingCount <= 0) {
			toast('最多只能上传9张图片');
			return;
		}
		const newImages = await chooseAndUploadImage({
			count: remainingCount,
			uploadText: '上传中...',
			sourceType: ['album']
		});
		params.images = [...params.images, ...newImages];
	} catch (err) {
		console.error('图片上传失败：', err);
		toast('图片上传失败');
	} finally {
		// 上传完成后可以选择是否重新聚焦
		// 这里不自动重新聚焦，让用户手动点击
	}
};
const params = reactive({
	id: undefined,
	content: '',
	images: []
});

const emit = defineEmits(['resetList']);

// 提交评论
const submitComment = () => {
	if (!btnactive.value) {
		toast('请输入评论内容');
		return;
	}
	isSubmitting.value = true;
	const submitData = {
		id: params.id,
		content: params.content,
		images: params.images.length > 0 ? params.images.join(',') : ''
	};
	if (sendType.value == 2) {
		article(submitData)
			.then((res) => {
				if (res.code == 200) {
					toast('已回复');
					emit('resetList',res.data,sendType.value);
					closePop();
				}
			})
			.catch((err) => {
				toast('评论提交失败');
				isSubmitting.value = false;
			});
	} else {
		articleReply(submitData)
			.then((res) => {
				if (res.code == 200) {
					toast('已发表评论');
					emit('resetList',res.data,sendType.value);
					closePop();
				}
			})
			.catch((err) => {
				toast('评论提交失败');
				isSubmitting.value = false;
			});
	}
};

const confirmInput = (e) => {
	submitComment();
};

defineExpose({ open, closePop });

onUnmounted(() => {
	uni.$off('pageShow');
	uni.$off('pageHide');
});
</script>
<style lang="scss" scoped>
.input_pop {
	position: fixed;
	width: 100%;
	background: #ffffff;
	padding: 30rpx 20rpx;
	box-sizing: border-box;
	/* 添加过渡动画使移动更平滑 */
	transition: bottom 0.3s ease;
	/* 确保在键盘上方 */
	z-index: 99999;
	/* 添加阴影提升视觉效果 */
	box-shadow: 0 -2rpx 20rpx rgba(0, 0, 0, 0.1);
}
.input {
	width: 100%;
	background: #f7f7f7;
	border-radius: 20rpx;
	padding: 16rpx 20rpx;
	box-sizing: border-box;
	transition: border-color 0.2s ease;
}
.input-inner {
	width: 100%;
	min-height: 60rpx; /* 最小高度 */
	max-height: 200rpx; /* 限制最大高度避免过高 */
	background: transparent;
	font-size: 28rpx;
	color: #333;
	border: none;
	resize: none;
	outline: none;
	/* 改善文本显示 */
	line-height: 1.5;
	/* 确保滚动流畅 */
	overflow-y: auto;
}
.imglist {
	display: flex;
	flex-wrap: wrap;
	margin-top: 15rpx;
	.items {
		width: 80rpx;
		height: 80rpx;
		margin-right: 10rpx;
		margin-bottom: 10rpx;
		position: relative;
		image {
			display: block;
			width: 80rpx;
			height: 80rpx;
			border-radius: 6rpx 6rpx 6rpx 6rpx;
		}
		.icon {
			width: 24rpx;
			height: 24rpx;
			top: -8rpx;
			right: -8rpx;
			position: absolute;
			z-index: 1;
		}
	}
	.items1 {
		width: 80rpx;
		height: 80rpx;
		border-radius: 6rpx;
		background: #ffffff;
	}
}
.button_f {
	margin: 14rpx auto;
	image {
		width: 48rpx;
		height: 48rpx;
	}
	.btn {
		width: 152rpx;
		height: 60rpx;
		background: #ffffff;
		border-radius: 80rpx 80rpx 80rpx 80rpx;
		border: 1px solid #d1d1d6;
		font-family: PingFang SC, PingFang SC;
		font-weight: 500;
		font-size: 28rpx;
		color: #d1d1d6;
		text-align: center;
		line-height: 60rpx;
	}
	.btn_active {
		background: #e3d0ad;
		color: #75613e;
		border: 1px solid #e3d0ad;
	}
}

/* 针对不同平台的微调 */
@media (platform: android) {
	.input_pop {
		padding-bottom: 20rpx; /* Android可能需要更多底部内边距 */
	}
}
@media (platform: ios) {
	.input_pop {
		padding-bottom: 10rpx; /* iOS可以少一些 */
	}
}
</style>
